﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GreenTeam.SharePointOnline.BookCompanion.Authentication;
using System.Xml;

namespace GreenTeam.SharePointOnline.BookCompanion.WebServicesClient
{
  public partial class ElencoCittaForm : Form
  {
    public ElencoCittaForm()
    {
      InitializeComponent();
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void OnVisualizzaCitta(object sender, EventArgs e)
    {
      var authenticationHelper = new Authenticator(
        txtUrl.Text, txtUser.Text, txtPassword.Text);

      var xmlDoc = new System.Xml.XmlDocument();
      var queryNode = xmlDoc.CreateNode(XmlNodeType.Element,"Query","");
      queryNode.InnerXml = "<FieldRef Name='Title' /><FieldRef Name='Regione' />";
      var viewFieldsNode = xmlDoc.CreateNode(XmlNodeType.Element,"ViewFields","");
      var queryOptionsNode = xmlDoc.CreateNode(XmlNodeType.Element,"QueryOptions","");
      
      var proxy = new GreenTeamLists.Lists();
      proxy.Url = txtUrl.Text + "/_vti_bin/Lists.asmx";
      proxy.CookieContainer = authenticationHelper.CookieContainer;
      var listItems = proxy.GetListItems(
        "Citta",
        null,
        queryNode,
        viewFieldsNode,
        "100",
        queryOptionsNode,
        null);
      this.DisplayListItems(listItems);
    }

    private void DisplayListItems(XmlNode listItems)
    {
      var document = new XmlDocument();
      document.Load(new XmlNodeReader(listItems));
      var nsManager = new XmlNamespaceManager(document.NameTable);
      nsManager.AddNamespace("z", "#RowsetSchema");
      nsManager.AddNamespace("rs", "urn:schemas-microsoft-com:rowset");
      nsManager.AddNamespace("root", "http://schemas.microsoft.com/sharepoint/soap/");
      var items = document.SelectNodes("/root:listitems/rs:data/z:row", nsManager);
      foreach (XmlNode item in items)
      {
        lvCitta.Items.Add(
          new ListViewItem(new String[] 
          {
            item.Attributes["ows_Title"].Value,
            item.Attributes["ows_Regione"].Value,
            item.Attributes["ows_Latitudine"].Value,
            item.Attributes["ows_Longitudine"].Value
          }));
      }
    }
  }
}
